/*
 * 人人信用管理有限公司版权所有.
 * 
 * @Description:
 * 
 * @author: liyuliang
 * 
 * @date: 20 Apr 2017 10:44:16 am
 * 
 * 注意：本内容仅限于人人信用管理有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */

package com.rrx360.common.config;

import java.net.URL;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ConfigNodeImpl implements ConfigNode {

  public static final Logger logger = LogManager.getLogger(ConfigNodeImpl.class);

  private String nodeId;

  private List<ConfigNode> dependencyList;

  private List<Object> configFileList;

  public ConfigNodeImpl() {

  }

  public ConfigNodeImpl(String nodeId, Object[] configFiles, ConfigNode[] dependencies) {
    this.nodeId = nodeId;
    configFileList = Arrays.asList(configFiles);
    dependencyList = Arrays.asList(dependencies);
  }

  public String getNodeId() {
    return nodeId;
  }

  public void setNodeId(String nodeId) {
    this.nodeId = nodeId;
  }


  public List<ConfigNode> getDependencyList() {
    return dependencyList;
  }

  public void setDependencyList(List<ConfigNode> dependencyList) {
    this.dependencyList = dependencyList;
  }

  public Configuration getConfiguration() {
    if (configFileList == null) {
      return null;
    }
    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setEncoding("UTF-8");
    config.setDelimiterParsingDisabled(true);
    for (Object o : configFileList) {
      URL url = null;
      if (o instanceof String) {
        String s = (String) o;
        url = this.getClass().getClassLoader().getResource(s);
        if (url == null) {
          continue;
        }
      } else if (o instanceof URL) {
        url = (URL) o;
      }
      if (url != null) {
        try {
          config.load(url);
        } catch (ConfigurationException e) {
          throw new RuntimeException(e);
        }
      }

    }
    return config;
  }



  public List<Object> getConfigFileList() {
    return configFileList;
  }

  public void setConfigFileList(List<Object> configFileList) {
    this.configFileList = configFileList;
  }

  @Override
  public String getConfigInfo() {
    if (configFileList == null) {
      return "[]";
    } else {
      StringBuilder builder = new StringBuilder();
      builder.append("[");
      for (Object o : configFileList) {
        builder.append(o + ",");
      }
      if (builder.length() > 1) {
        builder.deleteCharAt(builder.length() - 1);
      }
      builder.append("]");
      return builder.toString();
    }
  }



}
